// pages/submitOrder/submitOrder.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsInfo: null,
        addressInfo: {},
        inputValueNote: '',
        buyGoodsNum: 1,
        goodsPrice: 0,
        isShowBox: false,
        vouchersID: '',
        vouchersType: '',
        discount: 0,
        surplus: 0,
        fullRedPrice: 0,
        vouchersList: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var _goodsID = options.goodsID;
        var _selAttribute = options.selAttribute;
        var _merchantID = options.merchantID;
        var _totalPrice = options.totalPrice;
        var _goodsPrice = options.goodsPrice;
        var _isInvite = options.isInvite;
        var _goodsStandardList = JSON.parse(options.goodsStandardList);
        this.setData({
            goodsID: _goodsID,
            selAttribute: _selAttribute,
            merchantID: _merchantID,
            totalPrice: _totalPrice,
            goodsPrice: _goodsPrice,
            isInvite: _isInvite,
            goodsStandardList: _goodsStandardList,
            buyGoodsNum: _goodsStandardList[0].number
        });
        console.log(options);
        this.getGoodsInfoData(_goodsID, _merchantID);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getAddressInfoData('');
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    bindInputNote: function (e) {
        this.setData({
            inputValueNote: e.detail.value
        })
    },
    getMyVouchersData: function (_merchantID) {
        var that = this;
        // request
        var params = {
            userID: app.globalData.userID,
            type: 0,
            merchantID: _merchantID
        }
        app.network.requestPost(app.route.ROUTE_GET_MY_VOUCHERS, params, '', function (res) {
            //res就是我们请求接口返回的数据
            if (res.success) {
                var _vouchersList = res.context.vouchersList;
                for (var index in _vouchersList) {
                    if(index == 0) {
                        _vouchersList[index]['checked'] = true;
                    } else {
                        _vouchersList[index]['checked'] = false;
                    }
                }
                if (_vouchersList.length>0) {
                    _vouchersList.push({
                        vouchersID: '',
                        vouchersType: '',
                        discount: 20,
                        fullRedPrice: 200,
                        checked: false
                    })
                    that.setData({
                        vouchersList: _vouchersList,
                        vouchersID: _vouchersList[0].vouchersID,
                        vouchersType: _vouchersList[0].vouchersType,
                        discount: _vouchersList[0].discount,
                        fullRedPrice: _vouchersList[0].fullRedPrice
                    });
                } else {
                    that.setData({
                        vouchersList: _vouchersList
                    });
                }
                setTimeout(()=>{
                    that.getTotalPrice(that.data.buyGoodsNum);
                }, 200);
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },
    getAddressInfoData: function (_addressID) {
        var that = this;
        var params = {
            userID: app.globalData.userID,
            isInvite: that.data.isInvite,
            goodsID: that.data.goodsID,
            addressID: _addressID
        }
        app.network.requestPost(app.route.ROUTE_GET_ADDRESS_INFO, params, '', function (res) {
            //res就是我们请求接口返回的数据
            if (res.success) {
                var _addressInfo = res.context.address;
                that.setData({
                    addressInfo: _addressInfo
                });
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },
    getGoodsInfoData: function (_goodsID, _merchantID) {
        var that = this;
        var params = {
            userID: app.globalData.userID,
            goodsID: _goodsID
        }
        app.network.requestPost(app.route.ROUTE_GET_GOODS_INFO, params, '正在获取数据', function (res) {
            //res就是我们请求接口返回的数据
            if (res.success) {
                var _goodsInfo = res.context;
                that.setData({
                    goodsInfo: _goodsInfo
                });
                if (_goodsInfo.payType == 1 && _goodsInfo.isSeckill == 0) {
                    that.getMyVouchersData(_merchantID);
                }
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },
    //数量加
    addNumTap: function (e) {
        this.data.buyGoodsNum++;
        this.setData({
            buyGoodsNum: this.data.buyGoodsNum
        });
        this.getTotalPrice(this.data.buyGoodsNum);
    },
    //数量减
    subNumTap: function (e) {
        if (this.data.buyGoodsNum == 1) {
            return;
        }
        this.data.buyGoodsNum--;
        this.setData({
            buyGoodsNum: this.data.buyGoodsNum
        });
        this.getTotalPrice(this.data.buyGoodsNum);
    },
    //计算总价
    getTotalPrice: function (tempBuyGoodsNum) {
        var _totalPrice = 0;
        let tempDiscount = 0;
        if (this.data.vouchersID) {
            if (this.data.vouchersType == 1) {
                tempDiscount = this.data.discount;
                _totalPrice = this.data.goodsPrice * tempBuyGoodsNum - this.data.discount*100;
            } else {
                _totalPrice = this.data.goodsPrice * tempBuyGoodsNum * this.data.discount/10;
                tempDiscount = this.data.goodsPrice * tempBuyGoodsNum - _totalPrice
            }
        } else {
            _totalPrice = this.data.goodsPrice * tempBuyGoodsNum;
        }
        this.setData({
            surplus: tempDiscount,
            totalPrice: _totalPrice
        });
    },
    changeAddr: function (addressID) {
        this.getAddressInfoData(addressID);
    },
    goDetailTap: function(e) {
        if (this.data.goodsInfo.isInvite == 1) {
            wx.showToast({
                title: '不支持选地址'
            })
            return;
        }
        wx.navigateTo({
            url: '../myAddr/myAddr'
        })
    },
    submitOrderTap: function(e) {
        if (!app.globalData.userInfo.name) {
            wx.navigateTo({
                url: '../login/login',
            })
            return;
        } 
        if (app.globalData.userInfo.isLogin == 0) {
            wx.navigateTo({
                url: '../login/loginPhone?fromType=0',
            })
            return;
        }
        if (this.data.addressInfo.addressID == null) {
            wx.showToast({
                title: '请选择地址'
            })
            return;
        }
        var goodsStandardList = this.data.goodsStandardList;
        goodsStandardList[0].number = this.data.buyGoodsNum;
        goodsStandardList[0].subtotal = goodsStandardList[0].subtotal/100;
        if (this.data.goodsInfo.isSeckill) {
            var urlPath = app.route.ROUTE_BUY_SECKILL_GOODS;
            var params = {
                userID: app.globalData.userID,
                addressID: this.data.addressInfo.addressID,
                merchantID: this.data.merchantID,
                seckillID: this.data.goodsInfo.seckillID,
                goodsID: this.data.goodsInfo.goodsID,
                number: this.data.buyGoodsNum,
                goodsStandardList: JSON.stringify(this.data.goodsStandardList),
                remark: this.data.inputValueNote,
                totalPrice: this.data.totalPrice/100,
                payType: this.data.goodsInfo.payType
            }
        } else {
            var urlPath = app.route.ROUTE_PLACE_ORDER;
            var params = {
                userID: app.globalData.userID,
                addressID: this.data.addressInfo.addressID,
                merchantID: this.data.merchantID,
                goodsStandardList: JSON.stringify(this.data.goodsStandardList),
                remark: this.data.inputValueNote,
                totalPrice: this.data.totalPrice/100,
                payType: this.data.goodsInfo.payType,
                vouchersID: this.data.vouchersID,
                vouchersType: this.data.vouchersType
            }
        }
        console.log(params);
        var that = this;
        app.network.requestPost(urlPath, params, '正在提交订单', function (res) {
            //res就是我们请求接口返回的数据
            if (res.success) {
                if (that.data.goodsInfo.payType == 1) {
                    that.getPerpay(res.context.orderNo);//生成预支付
                } else {
                    wx.redirectTo({
                        url: '../order/order?tab=3',
                    })
                }
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },
    getPerpay: function (_orderNo) {
        var params = {
            userID: app.globalData.userID,
            orderNo: _orderNo,
            type: 0
        }
        var that = this;
        app.network.requestPost(app.route.ROUTE_WECHAT_PAY, params, '正在支付', function (res) {
            if (res.success) {
                var _package = 'prepay_id=' + res.obj.package;
                //调起微信支付  
                wx.requestPayment({
                    //相关支付参数  
                    timeStamp: res.obj.timeStamp,
                    nonceStr: res.obj.nonceStr,
                    package: _package,
                    signType: "MD5",
                    paySign: res.obj.sign,
                    //小程序微信支付成功的回调通知  
                    success: function (res) {
                        wx.redirectTo({
                            url: '../order/order?tab=3',
                        })
                    },
                    //小程序支付失败的回调通知  
                    fail: function (res) {
                        wx.redirectTo({
                            url: '../order/order?tab=1',
                        }) 
                    }
                })
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },

    openBoxTap: function(e) {
        this.setData({
            isShowBox: true
        });
    },

    coloseBoxTap: function(e) {
        this.setData({
            isShowBox: false
        });
    },

    radioChange: function(e) {
        let vouchersID = e.detail.value;
        this.data.vouchersList.forEach(item=>{
            if (vouchersID == item.vouchersID) {
                item.checked = true;
                this.setData({
                    vouchersID: item.vouchersID, 
                    vouchersType: item.vouchersType, 
                    discount: item.discount, 
                    fullRedPrice: item.fullRedPrice
                });
            } else {
                item.checked = false;
            }
        })
        this.setData({
            vouchersList: this.data.vouchersList
        });
        this.getTotalPrice(this.data.buyGoodsNum);
    }
})